# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
uuid    = require 'uuid'
router = express.Router()
module.exports = router

router.all '/', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    where_clause = "(
        f.name like $1 or f.notes like $1
    )"

    # 查询记录总数
    await client.query "select count(f.*) as count from pay_fee as f
        where #{ where_clause }", [
            '%' + res.locals.keyword + '%'
        ], defer err, result
    if err then done(client); return next(err)
    res.locals.total = result.rows[0].count

    # 查询当前页面中显示的记录
    await client.query "select f.*,
        count(distinct m.uuid) + count(distinct p2.uuid) as n_refs
        from pay_fee as f
        left join pay_merch as m on m.t20_fee = f.uuid
        left join pay_p2 as p2 on p2.t60_fee = f.uuid
        where #{ where_clause }
        group by f.serial, f.uuid
        order by f.serial offset $2::int limit $3::int", [
            '%' + res.locals.keyword + '%',
            res.locals.offset, res.locals.page_rows
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.render 'fee/index', records : result.rows


router.get '/new', (req, res, next) ->
    res.locals.breadcrumbs.push 'title': '新增手续费规则'
    res.render 'fee/new', record: {}


router.post '/new', (req, res, next) ->
    for k in ['name', 'debit_rules', 'cedit_rules']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "insert into pay_fee (
            uuid, name, debit_rules, cedit_rules, notes
        ) values (
            $1, $2, $3, $4, $5
        )", [
            uuid.v4(),
            req.body.name,
            req.body.debit_rules,
            req.body.cedit_rules,
            req.body.notes
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.redirect '/fee'


router.get '/edit/:id', (req, res, next) ->
    res.locals.breadcrumbs.push 'title': '修改手续费规则'

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "select * from pay_fee where serial = $1 or uuid = $2", [
            parseInt(req.params.id) or 0, req.params.id
        ], defer err, result
    if err then done(client); return next(err)
    done()

    if result.rows.length != 1
        return next(new Error("查无此手续费定义[#{req.params.id}]"))
    res.render 'fee/edit', record: result.rows[0]


router.post '/edit', (req, res, next) ->
    for k in ['serial', 'uuid', 'debit_rules', 'cedit_rules']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "update pay_fee set name = $1, debit_rules = $2,
            cedit_rules = $3, notes = $4
        where serial = $5 and uuid = $6", [
            req.body.name,
            req.body.debit_rules,
            req.body.cedit_rules,
            req.body.notes,
            req.body.serial,
            req.body.uuid,
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.redirect '/fee'


router.post '/delete', (req, res, next) ->
    res.type 'json'
    for k in ['serial', 'uuid']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err);

    await client.query \
        "delete from pay_fee where serial = $1 and uuid = $2", [
            req.body.serial, req.body.uuid,
        ], defer err, result
    if err then done(client); return next(err);
    done()
    res.json succ: true, redirect: '/fee'
